import React, { useEffect, useMemo, useRef, useState } from 'react'
import './index.less'
import { useSetState } from 'ahooks'
import { Select, Dropdown, Button } from 'antd'
const Option = Select.Option
import { DownOutlined } from '@ant-design/icons'
export default (props: any) => {
  const editor = useRef<any>()
  let [atIndex, setAtIndex] = useState(0)
  const [setDropdownOpen] = useState(false)
  let [isBlur, setIsBlur] = useState(true)
  let [selection, setSelection] = useState(null)
  const { changeValue, options } = props
  const inputFunc = (data: any, event: any) => {
    if (event.data === '#') {
      // 显示弹窗
      //   this.isShowAt = true
      setTimeout(() => {
        let dom: any = document.getElementsByClassName('at-pop-index')[0] // 获取成员列表弹窗，需要放在nextTick中
        // 设置位置
        dom.style.position = 'fixed'
        dom.style.left = Math.floor(data.left + 10) + 'px'
        dom.style.top = Math.floor(data.top) + 'px'
        dom.style.zIndex = 9999
      }, 10)
    } else {
      //   this.isShowAt = false
    }
  }
  const inputText = (event: any) => {
    console.log('子组件输入框的输入内容', editor.current.innerHTML)
    // changeValue(editor.innerHTML)
    let range = (window as any).getSelection().getRangeAt(0) // 获取当前光标
    let position = range.getBoundingClientRect() // 获取当前光标的位置
    inputFunc(position, event)
  }

  const onSelect = (item: any) => {
    setAtIndex(atIndex++)
    // 使用a标签表示@的成员
    let at = `<a name="at" value="${item.userName}" tabindex="-1" id="${atIndex}" contenteditable="false" href="javascript:void(0)">#${item.name}#</a>&#x200B;`
    insertContent(at, atIndex)
    console.log('onSelect', item)
    // this.$refs.inputBox.insertContent(`${item.name} `); // 有空格
  }
  const saveSelection = () => {
    if (!window.getSelection) {
      return null
    }
    let sel: any = window.getSelection()
    if (sel.getRangeAt && sel.rangeCount) {
      return sel.getRangeAt(0)
    }
  }
  const blurFunc = (e: any) => {}
  const inputBlur = () => {
    setIsBlur(true)
    setSelection(saveSelection())
    blurFunc(event)
  }
  const inputFocus = () => {
    setIsBlur(false)
  } // 恢复光标
  const restoreSelection = (range: any) => {
    if (range) {
      let sel: any = window.getSelection()
      sel.removeAllRanges()
      sel.addRange(range)
    }
  }
  const insertContent = (value: any, id: any = '') => {
    editor.current.focus()
    let range, node
    restoreSelection(selection) // 还原失焦前的光标位置
    range = (window as any).getSelection().getRangeAt(0)
    range.collapse(false) // 光标移动到最后
    node = range.createContextualFragment(value)
    let child = node.lastChild
    range.insertNode(node)
    // 将光标的起始位置设置在当前插入的元素后面
    if (child) {
      range.setEndAfter(child)
      range.setStartAfter(child)
    }

    let sel: any = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
    setTimeout(() => {
      if (/@<a name="at"/.test(editor.current.innerHTML)) {
        // 使用正则替换，将已经输入的@替换掉
        // 如果直接赋值修改innerHTML，则光标默认会回到开头。因此需要额外处理光标
        editor.current.innerHTML = editor.current.innerHTML.replace(/@<a name="at"/, '<a name="at"')
        let el: any = document.getElementById(id)
        range = document.createRange()
        sel = window.getSelection()
        // 将光标重新定位到自定义的a标签后面
        range.setStartAfter(el)
        range.setEndAfter(el)

        sel.removeAllRanges()
        sel.addRange(range)
      }
    }, 10)
    changeValue(editor.current.innerHTML)
  }
  const changeSelect = (item: any) => {
    setAtIndex(atIndex++)
    // 使用a标签表示#的话题
    let at = `<a name="at" value="${item.key}" tabindex="-1" id="${atIndex}" contenteditable="false" href="javascript:void(0)">#${item.key}#</a>`
    insertContent(at, atIndex)
    // this.$refs.inputBox.insertContent(`${item.name} `); // 有空格
  }
  //   下拉选项
  const menuItems = useMemo(() => {
    return options.map((item: any) => ({
      label: item.name,
      key: item.value
    }))
  }, [options])
  return (
    <div className="topic-edit-container">
      <pre ref={editor} className="topic-content" contentEditable={true} onInput={inputText} onBlur={inputBlur} onFocus={inputFocus}></pre>
      <Dropdown
        getPopupContainer={() => document.querySelector('#root') as any}
        className="options"
        menu={{
          items: menuItems,
          onClick: changeSelect
        }}
      >
        <Button>
          插入变量
          <DownOutlined style={{ color: '#bbb' }} />
        </Button>
      </Dropdown>
    </div>
  )
}
